package com.example.lcpharmacy.service;


import com.example.lcpharmacy.entity.GoodsInfoEntity;
import com.example.lcpharmacy.entity.UserEntity;
import com.example.lcpharmacy.mapper.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

@Service
public class UserService {

    @Autowired
    HttpServletRequest request;

    @Autowired
    private UserDao userDao;

    public String saveRegister(UserEntity userEntity) {
        //1.判断用户名是否唯一
        UserEntity user = userDao.selectByName(userEntity);
        if (Objects.nonNull(user)) {
            return null;
        }
        //2.将用户信息添加到数据库
        int affects = userDao.insertUser(userEntity);
        //3.判断是否添加成功
        if (affects == 0) {
            return null;
        }
        HttpSession session = request.getSession(true);
        session.setAttribute("currentUser",userEntity);
        return "注册成功！";
    }

    public String saveUserModify(UserEntity userEntity) {
        List<UserEntity> checkItems1 = userDao.checkName(userEntity);
        if (userEntity.getId() != 0) {
            if (!(checkItems1.isEmpty())) {
                return "用户名已被使用！";
            } else {
                userDao.updateUser(userEntity);
                return "用户信息更新成功！";
            }
        } else {
            if (!(checkItems1.isEmpty())) {
                return "用户名已被使用！";
            } else {
                userDao.insertUserInfo(userEntity);
                return "用户添加成功！";
            }
        }
    }
}
